package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dtos.UserSearchDto;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.service.ApUserSearchService;
import com.usian.search.service.ArticleSearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zlm
 * @version 1.0
 * @date 2022/9/27 19:53
 */
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;
    @Autowired
    private BehaviorFeign behaviorFeign;


    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto == null || StringUtils.isBlank(dto.getSearchWords()))return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"搜索关键字不能为空");
        //构建搜索请求对象，需要指定索引库名称。
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //条件构造器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //根据关键字分词查询-->title content
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);
        //查询小于minBehotTime的数据
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
        boolQueryBuilder.filter(rangeQueryBuilder);
        searchSourceBuilder.query(boolQueryBuilder);
        //按照发布时间倒叙查询
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(dto.getPageSize());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //封装方法数据
        List<Map> articleList = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);
            articleList.add(map);
        }
        if (dto.getPageNum() == 0){
            Integer id = AppThreadLocalUtils.getUser().getId();
            if (id == null) id = -1;
            Integer equipmentId = dto.getEquipmentId();
            if (equipmentId == null) equipmentId = -1;
            ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(id, equipmentId);
            apUserSearchService.insert(behaviorEntry.getId(),dto.getSearchWords());
        }
        return ResponseResult.okResult(articleList);
    }
}
